#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void BubbleSort(vector<int> &nums)
{
    int end = nums.size() - 1;
    for (; end >= 0; end--)
    {
        bool flag;
        for (int i = 0; i < end; i++)
        {
            if (nums[i] > nums[i + 1])
            {
                swap(nums[i], nums[i + 1]);
                flag = true;
            }
        }
        if (!flag)
            break;
    }
}

// int main()
// {
//     vector<int> nums{8,7,6,3,4,9,1,2};
//     BubbleSort(nums);
//     for(auto e:nums)
//         cout<<e<<" ";
//     return 0;
// }

//////////////////////////
// 二分

// 朴素版
int BinSearch(vector<int> &nums, int target)
{
    int left = 0, right = nums.size() - 1;
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (nums[mid] < target)
            left = mid + 1;
        else if (nums[mid] > target)
            right = mid - 1;
        else
            return mid;
    }
    return -1;
}
// 版本B
int BinSearchB(vector<int> &nums, int target)
{
    int left = 0, right = nums.size() - 1;
    while (left < right - 1)
    {
        int mid = left + (right - left) / 2;
        if (nums[mid] > target)
            right=mid;
        else
            left=mid;
    }
    return nums[left] == target ? left : -1;
}
// 版本C
int BinSearchC(vector<int> &nums, int target)
{
    int left = 0, right = nums.size() - 1;
    while (left < right)
    {
        int mid = left + (right - left) / 2;
        if (nums[mid] > target)
            right=mid;
        else
            left=mid+1;
    }
    return --left;
}

// int main()
// {
//     vector<int> nums{8, 7, 6, 3, 4, 9, 1, 2};
//     BubbleSort(nums);
//     cout<<BinSearch(nums, 6)<<endl;

//     cout<<BinSearchB(nums, 6)<<endl; 

//     cout<<BinSearchC(nums, 6)<<endl;

//     return 0;
// }

//[left,mid][mid+1,right]
//后序遍历
vector<int> tmp(100);
void MergeSort(vector<int>&nums,int left,int right)
{
    if(left>=right)
        return ;

    int mid=(left+right)/2;
    MergeSort(nums,left,mid);
    MergeSort(nums,mid+1,right);

    int cur1=left,cur2=mid+1,i=0;
    while(cur1<=mid&&cur2<=right)
        tmp[i++]=nums[cur1]<nums[cur2]?nums[cur1++]:nums[cur2++];
    
    while(cur1<=mid)
        tmp[i++]=nums[cur1++];
    while(cur2<=mid)
        tmp[i++]=nums[cur2++];
    //将tmp的数据还原到nums
    for(int j=left;j<=right;j++)
        nums[j]=tmp[j-left];
}

int main()
{
    vector<int> nums{8,7,6,3,4,9,1,2};
    MergeSort(nums,0,nums.size()-1);
    for(auto e:nums)
        cout<<e<<" ";
    return 0;
}